<template>
  <el-form :model="ruleForm" ref="ruleForm" :label-position="labelPosition" :class="isEdit?'':'formItem'"
           :rules="rules">
    <!-- 一般维修   -->
    <el-card class="box-card" shadow="never">
      <div slot="header" class="header-card">
        <span class="header-card-title">维修信息</span>
      </div>
      <el-row :gutter="24">
        <el-col>
          <el-form-item label="维修类别:">
            <el-radio-group v-model="ruleForm.maintenanceType" disabled>
              <el-radio label="2">一般维修</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

      </el-row>
      <!-- 维修类型 一般维修 -->
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="预计维修开始时间:" prop="expectStartTime">
            <el-date-picker type="date" v-model="ruleForm.expectStartTime" v-if="isEdit" value-format='yyyy-MM-dd'
                            style="width: 100%;" placeholder="选择预计维修开始时间">
            </el-date-picker>
            <span v-else>{{ ruleForm.expectStartTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预计维修结束时间:" prop="expectEndTime">
            <el-date-picker type="date" v-model="ruleForm.expectEndTime" v-if="isEdit" value-format='yyyy-MM-dd'
                            style="width: 100%;" placeholder="选择预计维修结束时间">
            </el-date-picker>
            <span v-else>{{ ruleForm.expectEndTime }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="签约维修厂/维修厂:" prop="maintenanceShopId">
            <el-select v-if="isEdit" v-model="ruleForm.maintenanceShopId" @change="handleChange" style="width: 100%"
                       placeholder="请选择输入维修厂">
              <el-option v-for="item in options" :key="item.supplierId" :label="item.supplierName"
                         :value="item.supplierId"/>
            </el-select>
            <span v-else>{{ ruleForm.maintenanceShop }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="故障现象:" prop="faultPhenomenon">
            <el-input v-if="isEdit" v-model="ruleForm.faultPhenomenon" placeholder="输入故障现象"></el-input>
            <span v-else>{{ ruleForm.faultPhenomenon }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维修厂故障诊断:" prop="maintenanceFaultDiagnosis">
            <el-input v-if="isEdit" v-model="ruleForm.maintenanceFaultDiagnosis"
                      placeholder="输入维修厂故障诊断"></el-input>
            <span v-else>{{ ruleForm.maintenanceFaultDiagnosis }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维修厂报价:" prop="maintenanceQuoter">
            <el-input v-if="isEdit" v-model="ruleForm.maintenanceQuoter" @change="changeAmount('maintenanceQuoter')"
                      v-thousand placeholder="输入维修厂报价"></el-input>
            <span v-else>{{ format_thousand(ruleForm.maintenanceQuoter) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否符合索赔理由:" prop="reasonForClaim">
            <el-select v-model="ruleForm.reasonForClaim" placeholder="选择是否符合索赔理由" style="width: 100%;"
                       v-if="isEdit">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="2"></el-option>
            </el-select>
            <span v-else>{{
                ruleForm.reasonForClaim == "1" ? '是' : ruleForm.reasonForClaim == "2" ? '否' : ''
              }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" prop="claimantReason">
          <el-form-item label="不符合索赔理由:">
            <el-input v-if="isEdit" v-model="ruleForm.claimantReason" placeholder="输入不符合索赔理由"></el-input>
            <span v-else>{{ ruleForm.claimantReason }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否有同车型(处置车辆)对换配件:">
            <el-select v-model="ruleForm.swappingAccessories" placeholder="选择是否有同车型(处置车辆)对换配件"
                       style="width: 100%;"
                       v-if="isEdit">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="2"></el-option>
            </el-select>
            <span v-else>{{
                ruleForm.swappingAccessories == "1" ? '是' : ruleForm.swappingAccessories ==
                "2" ? '否' : ''
              }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="综合建议方案:" prop="comprehensiveRecommendations">
            <el-input v-if="isEdit" placeholder="综合建议方案" type="textarea" :rows="4"
            :maxlength="500"  v-model="ruleForm.comprehensiveRecommendations"></el-input>
            <span v-else>{{ ruleForm.comprehensiveRecommendations }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注:" prop="generalMaintenanceRemark">
            <el-input v-if="isEdit" placeholder="输入备注" type="textarea" :rows="4"
            :maxlength="500"  v-model="ruleForm.generalMaintenanceRemark"></el-input>
            <span v-else>{{ ruleForm.generalMaintenanceRemark }}</span>
          </el-form-item>
        </el-col>
      </el-row>

    </el-card>

    <!--维修项目明细-->
    <el-card class="box-card" shadow="never">
      <div slot="header" class="header-card">
        <div style="width:100%;display: flex;justify-content: space-between">
          <span class="header-card-title">维修项目明细</span>
        </div>
      </div>
      <div class="div_body">
        维修合计费用: ￥ <span v-if="totalExpense > 0">{{ totalExpense }}</span>
      </div>
      <el-row :gutter="24" style="margin-bottom: 16px;">
        <el-col>
          <el-table size="mini" :data="ruleForm.carMaintenanceProjectList" border style="width: 100%"
                    :header-cell-class-name="headerClass">
            <el-table-column align="center" label="操作" width="68" v-if="isEdit">
              <template #default="{row}">
                <el-button size="mini" type="text" @click="delDecoration(row, $index)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" label="维修项目名称" min-width="160" prop="maintenanceName">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'carMaintenanceProjectList.'+$index+'.maintenanceName'"
                              :rules="{required: true,  trigger: 'blur'}">
                  <el-input v-model="row.maintenanceName" v-if="isEdit" size="mini"></el-input>
                  <span v-else>
                    {{ row.maintenanceName }}
                  </span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="金额/元" min-width="100" prop="price">
              <template #default="{row,$index}">
                <span>
                  {{ format_thousand(handlePice(row, $index)) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="单价材料费" min-width="120" prop="materialCost">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'carMaintenanceProjectList.'+$index+'.materialCost'"
                              :rules="{required: true,  trigger: 'blur'}">
                  <el-input v-model="row.materialCost" v-if="isEdit" v-thousand
                            @change="changeTable(row, $index, 'materialCost')" size="mini"></el-input>
                  <span v-else>
                    {{ format_thousand(row.materialCost) }}
                  </span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="数量" min-width="120" prop="maintNum">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'carMaintenanceProjectList.'+$index+'.maintNum'"
                              :rules="{required: true,  trigger: 'blur'}">
                  <el-input v-model="row.maintNum" v-if=" isEdit" @change="changeTable(row, $index, 'maintNum')"
                            size="mini"></el-input>

                  <span v-else>{{ row.maintNum }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="单价工时费" min-width="120" prop="laborCost">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'carMaintenanceProjectList.'+$index+'.laborCost'"
                              :rules="{required: true,  trigger: 'blur'}">
                  <el-input v-model="row.laborCost" v-if="isEdit" v-thousand
                            @change="changeTable(row, $index, 'laborCost')" size="mini"></el-input>
                  <span v-else>
                    {{ format_thousand(row.laborCost) }}
                  </span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="配件号" min-width="140">
              <template #default="{row}">
                <el-input v-model="row.partNumber" v-if="isEdit" size="mini"></el-input>
                <span v-else>
                  {{ row.partNumber }}
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="品牌" min-width="120">
              <template #default="{row}">
                <el-input v-model="row.maintBrand" v-if="isEdit" size="mini"></el-input>
                <span v-else>
                  {{ row.maintBrand }}
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="型号" min-width="120">
              <template #default="{row}">
                <el-input v-model="row.maintModel" v-if="isEdit" size="mini"></el-input>
                <span v-else>
                  {{ row.maintModel }}
                </span>
              </template>
            </el-table-column>

            <el-table-column align="center" label="详细信息" min-width="150">
              <template #default="{row}">
                <el-input v-model="row.detailedInfo" v-if="isEdit" size="mini"></el-input>
                <span v-else>
                  {{ row.detailedInfo }}
                </span>
              </template>
            </el-table-column>
            <template v-slot:append v-if="isEdit">
              <div class="flex-xy-center" style="height: 30px">
                <e-button type="text" @click="addDecoration">
                  新增
                </e-button>
              </div>
            </template>
          </el-table>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col>
          <el-form-item label="上传附件:">
            <image-common v-model="ruleForm.maintenanceProjectUrl" :limit="20" :disabled="!isEdit" :upType="2"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>
  </el-form>
</template>

<script>
import {effectDate} from "@/utils/libs/effectDate.js";
import {getInsuranceSelectList} from "@/api/cwgd/insuranceSelect";
import {toNumberAdd, toNumberRide} from "@/utils/utils";

export default {
  name: "normalRepair", //一般维修


  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: "",
    },
  },
  computed: {
    ruleForm: {
      get() {
        let that = this;
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key);
          },
          set(target, key, value) {
            if (value) {
              that.handleClearValidate(key);
            }
            that.$emit("input", {...target, [key]: value});
            return true;
          },
        });
        return proxy;
      },
    },
    labelPosition() {
      if (this.isEdit) {
        return "top";
      } else {
        return "left";
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool;
    },
  },
  data() {
    var start = (rule, value, callback) => {
      let that = this;
      effectDate(
          rule,
          value,
          callback,
          that.ruleForm.expectStartTime,
          that.ruleForm.expectEndTime,
          "预计维修开始时间",
          "预计开维结束时间"
      );
    };
    var end = (rule, value, callback) => {
      let that = this;
      effectDate(
          rule,
          value,
          callback,
          that.ruleForm.expectStartTime,
          that.ruleForm.expectEndTime,
          "预计维修开始时间",
          "预计开维结束时间"
      );
    };
    return {
      isShow: true,
      totalExpense: 0,
      headerList: [
        "maintenanceName",
        "price",
        "materialCost",
        "laborCost",
        "maintNum",
      ],
      rules: {
        //维修类型 一般维修
        expectStartTime: [
          {
            required: this.state === "write",
            validator: start,
            trigger: "change",
          },
        ],
        expectEndTime: [
          {
            required: this.state === "write",
            validator: end,
            trigger: "change",
          },
        ],
        maintenanceShopId: [
          {
            required: this.state === "write",
            message: "请输入签约维修厂/维修厂",
            trigger: "blur",
          },
        ],
        faultPhenomenon: [
          {
            required: this.state === "write",
            message: "请输入故障现象",
            trigger: "blur",
          },
        ],
        maintenanceFaultDiagnosis: [
          {
            required: this.state === "write",
            message: "请输入维修厂故障诊断",
            trigger: "blur",
          },
        ],
        maintenanceQuoter: [
          {
            required: this.state === "write",
            message: "请输入维修厂报价",
            trigger: "blur",
          },
        ],
        reasonForClaim: [
          {
            required: this.state === "write",
            message: "请选择是否符合索赔理由",
            trigger: "change",
          },
        ],
        comprehensiveRecommendations: [
          {
            required: this.state === "write",
            message: "请输入综合建议方案",
            trigger: "blur",
          },
        ],
        maintenanceProjectUrl: [
          {
            required: this.state === "write",
            message: "请选择定损单",
            trigger: "change",
          },
        ],
        claimantReason: [
          {
            required: this.isEdit,
            message: "请输入不符合索赔理由",
            trigger: "blur",
          },
        ],
      },
      options: [],
    };
  },
  created() {
    this.handleList();
  },
  mounted() {
    this.handleTotalExpense();
    this.handleCount(this.value.carMaintenanceProjectList);
  },

  methods: {
    handlePice(val, index) {
      let num = 0;
      num = toNumberAdd(
          toNumberRide(Number(val.materialCost || 0), Number(val.maintNum || 0)),
          Number(val.laborCost || 0))
      this.$set(this.value.carMaintenanceProjectList[index], "price", num);
      return num;
    },

    handleCount(val) {
      let num = 0, total = 0;
      for (let item of val) {
        num = (Number(item.price) * 100).toFixed(0)
        total += Number(num)
      }
      this.ruleForm.maintenanceQuoter = total / 100;
    },

    handleList() {
      getInsuranceSelectList({businessTypeCode: "4"}).then((res) => {
        if (res.code === 200) {
          this.options = res.data;
        }
      });
    },

    handleChange(val) {
      this.value.maintenanceShopId = val;
      this.value.maintenanceShop = this.options.find(
          (item) => item.supplierId === val
      ).supplierName;
    },
    //表头必填*
    headerClass({row, column, rowIndex, columnIndex}) {
      for (let i = 0; i < row.length; i++) {
        if (
            this.headerList.includes(row[i].property) &&
            i == columnIndex &&
            this.isEdit
        ) {
          return "header-class";
        }
      }
    },

    //新增
    addDecoration() {
      let obj = {
        maintenanceName: "",
        price: "",
        materialCost: "",
        laborCost: "",
        partNumber: "",
        maintBrand: "",
        maintModel: "",
        maintNum: "",

        detailedInfo: "",
        disabled: true,
      };
      this.ruleForm.carMaintenanceProjectList.push(obj);
    },

    //删除
    delDecoration(row, key) {
      this.ruleForm.carMaintenanceProjectList.splice(key, 1);
      this.handleCount(this.value.carMaintenanceProjectList);
    },

    changeAmount(str) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      if (!msg.test(this.ruleForm[str])) {
        this.ruleForm[str] = "";
      } else {
        this.ruleForm[str] = this.ruleForm[str]
            .toString()
            .match(/^\d+(?:\.\d{0,2})?/)[0];
        this.sumPrice();
      }
    },

    //定损总计
    sumPrice() {
      let num = 0;
      num =
          Number(this.ruleForm.vehicleAssessmentPrice) +
          Number(this.ruleForm.residualValue) +
          Number(this.ruleForm.carOther);
      this.ruleForm.assessmentTotalPrice = num
          .toString()
          .match(/^\d+(?:\.\d{0,2})?/)[0];
    },

    //维修合计费用
    handleTotalExpense() {
      this.totalExpense = 0;
      for (let i = 0; i < this.ruleForm.carMaintenanceProjectList.length; i++) {
        const priceInCents = Math.round(Number(this.ruleForm.carMaintenanceProjectList[i].price) * 100);
        this.totalExpense += priceInCents;
      }
      this.totalExpense /= 100; //
    },

    //数字正则
    changeTable(row, key, field) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      if(field === 'maintNum'){
        msg = /^(?:[1-9]\d*|-(?!0)\d+)$/
      }
      // if (field == "price") {
      if (msg.test(Number(row[field]))) {
        if (Number(row[field]) >= 0) {
          let _value = row[field].toString().match(/^\d+(?:\.\d{0,2})?/)[0];
          row[field] = _value;
        } else {
          row[field] = "";
        }
      } else {
        row[field] = "";
      }
      // }
      this.handleTotalExpense();
      this.handleCount(this.ruleForm.carMaintenanceProjectList);
    },

    //表单效验
    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            reject();
          }
        });
      });
    },

    //表单效验
    valid() {
      return new Promise((resolve) => {
        this.$refs.ruleForm.validate((valid) => {
          resolve(valid);
        });
      });
    },
    handleClearValidate(str) {
      this.$refs.ruleForm.clearValidate(str);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/cwgd/formScss.scss";

::v-deep .header-class {
  .cell::before {
    content: "*";
    color: red;
    padding-right: 2px;
    font-size: 14px;
  }
}
</style>


